%% 函数说明：多领域交叉结构中的部分匹配法（PMX）
%% 举例：
%   parent1 = [1,2,3,4,5,6,7,8,9],parent2 = [5,4,6,9,2,1,7,8,3]
%   假设选中的元件位置r1=3,r2=6,则生成的子代sequen = [3,5,6,9,2,1,7,8,4]
function sequen = LSO_MNSC_PMX(parent1,parent2)
        r1 = randperm(length(parent1),1);
        r2 = randperm(length(parent2),1);
%         r1 = 3;%测试用
%         r2 = 6;
        m = min(r1,r2);
        M = max(r1,r2);
%         if M<length(parent1)-3
%             M = m+3;
%         end
        Intersec1 = parent1(m:M);%取出父代1的交叉段
        Intersec2 = parent2(m:M);%取出父代2的交叉段
        parent1_left = parent1;
        parent2_left = parent2;
        parent1_left(m:M) = [];%取出交叉段后剩下的元件,交叉段所有原件shandiao
        parent2_left(m:M) = [];
        parent1_child = parent1;
        parent2_child = parent2;
        parent1_child(m:M) = Intersec2;%互换交叉段生成初始子代1、子代2
        parent2_child(m:M) = Intersec1;
        child1_Intersec_left = parent1_child;%将交叉后子代的交叉段保留，其它设为0
        child1_Intersec_left(1:m-1)= 0;
        child1_Intersec_left(M+1:end)= 0;
        child2_Intersec_left = parent2_child;
        child2_Intersec_left(1:m-1)= 0;
        child2_Intersec_left(M+1:end)= 0;
        len = length(parent1_left);
        %遍历交叉段，解决子代复制父代剩余元件段与交叉段元件产生冲突的问题
        for i = 1:len
            child_conflict_index = find(child1_Intersec_left == parent1_left(i) );%冲突元件在初始子代的位置
            parent_conflict_index = find(parent1 == parent1_left(i) );%冲突元件在父代的位置
            if length(child_conflict_index) ==0 %没有冲突
                %不必做什么
            else %有冲突  
               while child_conflict_index  %若选中的父代元件还与子代交叉段冲突，继续替换
                   if length(child_conflict_index)
                        child_conflict_index_temp = child_conflict_index;
                   end
                   parent_compo = parent1(child_conflict_index);%找到冲突元件子代位置对应父代同一位置的元件
                   child_conflict_index = find(child1_Intersec_left == parent_compo);%判断该元件是否与子代交叉段冲突
               end
               %解决冲突，跳出while循环后，
               parent1_child(parent_conflict_index) = parent1(child_conflict_index_temp);
            end
           
        end
        sequen = parent1_child;
end

            
        
        